﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ZXW.DotNet.Common.Basic.Serialize
{
    public class BinarySerialize<T> : ISerialize<T, byte[]>
    {
        #region ISerialize<T,byte[]> 成员
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public byte[] Serialize(T data)
        {
            MemoryStream stream = new MemoryStream();
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, data);
            stream.Flush();
            byte[] theBytes = stream.ToArray();
            stream.Close();
            return theBytes;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public T DeSerialize(byte[] data)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(data);
            object obj = formatter.Deserialize(stream);
            stream.Close();
            return (T)obj;
        }

        #endregion
    }
}
